import jwt
from fastapi import status, HTTPException

from scaner.core.config.project_config import settings
from .database import get_token_by_chat_id


def encode_jwt(
    payload: dict,
    private_key: str = settings.auth_jwt.private_key_path.read_text(),
    algorithm: str = settings.auth_jwt.algorithm,
):

    to_encode = payload.copy()

    encoded = jwt.encode(
        to_encode,
        private_key,
        algorithm=algorithm,
    )

    return encoded


async def get_token(chat_id: int):
    if token := await get_token_by_chat_id(chat_id):
        return token

    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="К чату нет привязанных аккаунтов",
    )
